/**
 * @Description: 支付信息的编辑
 * @author longfa liang
 * @date 2021/7/15
 */
var redis = require('../db/redis')
var pu = require('../tool/public')
var config = require('../config/config')
var mg = require('../db/userdb')
var wx = require('../tool/wxResult')
var aliplay = require('../tool/aliplay')

class play {

    /*新增版本*/
    add_play_ifon_version (req, res, next) {
        console.log(req.body)
        var price = req.body.price
        var name = req.body.name
        var module = req.body.module
        try {

            if (typeof module == 'string') {
                module = JSON.parse(module)
            }
        } catch (e) {
            console.error(e)
            pu.fail('参数不正确', res)
            return
        }
        let isnull = pu.isnull([price, name, module])
        var id = pu.uuid()
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        redis.rpush('ADMIN_PLAYINFO_VERSION', JSON.stringify({ price: price, name: name, module: module, id: id }))
        pu.success('成功', { price: price, name: name, module: module, id: id }, res)
    }

    /*新增人数*/
    add_play_ifon_people (req, res, next) {
        var sum = req.body.sum
        var discount = req.body.discount
        let isnull = pu.isnull([sum, discount])
        req.body.id = pu.uuid()
        if (isnull) {
            pu.fail('参数不正确' + isnull, res)
            return
        }
        redis.rpush('ADMIN_PLAYINFO_PEOPLE', JSON.stringify(req.body))
        pu.success('成功', {}, res)
    }

    /*获取时长*/
    add_play_ifon_time (req, res, next) {
        var time = req.body.time
        var discount = req.body.discount
        let isnull = pu.isnull([time, discount])
        req.body.id = pu.uuid()
        if (isnull) {
            pu.fail('参数不正确' + isnull, res)
            return
        }
        redis.rpush('ADMIN_PLAYINFO_TIME', JSON.stringify(req.body))
        pu.success('成功', {}, res)
    }

    /*获取支付信息*/
    async get_play_ifon (req, res, next) {
        let people = await redis.lrange('ADMIN_PLAYINFO_PEOPLE')
        let time = await redis.lrange('ADMIN_PLAYINFO_TIME')
        let version = await redis.lrange('ADMIN_PLAYINFO_VERSION')
        console.log({ people, time, version, testTime: config.test.testTime, testPople: config.test.testPople, testVersion: config.test.testversion });
        pu.success('成功', { people, time, version, testTime: config.test.testTime, testPople: config.test.testPople, testVersion: config.test.testversion }, res)
    }


    /*查询支付信息*/
    async admin_find_payment_info (req, res, next) {

        var status = req.body.status
        var type = req.body.type
        var where = {}
        if (status) {
            where.status = Number(status)
        }
        if (type) {
            where.type = Number(type)
        }
        let info = await mg.find('admin_play_info', where)
        pu.success('OK', info, res)
    }

    /*通过用户id查询支付信息 */
    async find_payment_info (req, res, next) {
        let userid = req.headers.userid
        var status = req.body.status
        var _id = req.body._id
        var where = {}

        if (_id) {
            where._id = mg.ObjectID(_id)
            let info = await mg.find('admin_play_info', where)
            pu.success('OK', info, res)
            return
        }
        if (status) {
            where.status = Number(status)
        }
        let info = await mg.find('admin_play_info', where)
        pu.success('OK', info, res)
        return
    }

    /*支付到账*/
    async palysuccesc (req, res, next) {
        let data = req.query
        let info = await mg.findOne('admin_play_info', { _id: mg.ObjectID(data.out_trade_no) })

        if (!info || info.status == 3) {
            res.end()
            return
        } else {
            if (data.trade_status == 'TRADE_SUCCESS' && data.out_trade_no == info._id.toString()) {
                this.payment_succsec(res, info, 3, data.out_trade_no)
            } else {

                res.end()
            }
        }
    }

    /**
     * 统一支付成功后创建团队
     * @param res 请求对象
     * @param orderinfo 订单信息
     * @param status  状态（可选） 0审核中 1审核不通过直接驳回 2 补差价 3通过
     * @param _id 用户id
     * @returns {Promise<void>}
     */
    async payment_succsec (res, orderinfo, status, _id) {
        /* 通过后需要自动创建团队 并且自动成为团队管理员 并且新建一个权限并且绑定*/


        let userinfo = await mg.findOne('users', { _id: mg.ObjectID(orderinfo.userid) })
        let teaminfo = {
            team_name: orderinfo.group_name //团队名字
            , userid: userinfo._id // 团队负责人id
            , phone: userinfo.phone // 负责人电话
            , use_stop_time: Number(orderinfo.t_info.time) + new Date().getTime() //授权到期时间
            , auth_sum: Number(orderinfo.p_info.sum)//授权人数
            , use_auth_sum: 1//已经人数
            , 'meal_name': orderinfo.v_info.name,//套餐名称
            'money': orderinfo.money//支付金额
            , 'jur': orderinfo.v_info.module
        }
        /*创建团队*/
        let inserraw = await mg.insertOne('team', teaminfo)

        let updateuserinfo = {
            $set: { last_group_id: inserraw.insertedId, last_group_name: teaminfo.team_name },
            $push: { group_list: inserraw.insertedId }
        }
        /*修改用户最后所在组织*/
        await mg.updateOne('users', { _id: userinfo._id }, updateuserinfo)
        /*创建超级管理员权限*/
        let insert = { teamid: inserraw.insertedId, name: '超级管理员', module: orderinfo.v_info.module, adduserid: userinfo._id, is_delete: 0 }
        let inserinfo = await mg.insertOne('jurinfor', insert)
        insert._id = inserinfo.insertedId
        /*给管理员绑定上权限*/
        await redis.hset('JURINFO_' + inserraw.insertedId.toString(), inserinfo.insertedId.toString(), JSON.stringify(orderinfo.v_info.module))


        var team_user = {
            name: userinfo.name,
            userid: userinfo._id,
            job_number: '', // 员工编号
            id_no: userinfo.id_no || '',//身份证号码
            residential_address: '',//居住地址
            phone: Number(userinfo.phone),
            // department_name: department.department_name, //部门ID
            department_id: '',
            // team_name: teaminfo.team_name, //团队
            team_id: inserraw.insertedId,
            // duties_name: dutiesinfo.duties_name,//岗位
            duties_id: '',//岗位id
            isreg: 1,//是否注册 1注册 0未注册
            on_the_job: 0 //0在职 1离职
            , desc: ''//备注
            , role_id: ''
            , entry_time: new Date().getTime() //创建日期
        }

        /*用户表创建用户*/
        let teamuserinfo = await mg.insertOne('team_users', team_user)

        /*用户直接绑定上权限*/
        await redis.hset('JURINFO_USER_' + inserraw.insertedId.toString(), teamuserinfo.insertedId.toString(), inserinfo.insertedId.toString())


        /*修改订单*/
        await mg.updateOne('admin_play_info', { _id: mg.ObjectID(_id) }, { $set: { status: Number(status) } })
        console.log('支付订单成功', JSON.stringify(teaminfo))
        if (res) {
            delete teaminfo.phone
            pu.success('OK', teaminfo, res)
        }

    }

    async update_payment_info (req, res, next) {
        let _id = req.body._id
        let status = Number(req.body.status)
        let desc = req.body.desc
        let img_url = req.body.img_url

        let isnull = pu.isnull([_id, status])
        if (isnull) {
            pu.fail('参数不正确' + isnull, res)
            return
        }

        let orderinfo = await mg.findOne('admin_play_info', { _id: mg.ObjectID(_id) })
        if (orderinfo.status == 3) {
            pu.fail('订单状态已经通过无法修改', res)
            return
        }
        if (orderinfo.status == status) {
            pu.fail('状态不正确', res)
            return
        }
        if (status == 3 && orderinfo.status != 0) {
            pu.fail('状态不是正在审核中 无法审核通过', res)
            return
        }

        if (status == 1 || status == 2 || status == 0) { //审核不通过或者重新提交
            var update = { $set: { status: Number(status), desc: desc } }
            if (status == 0) {
                update = { $set: { status: Number(status), desc: desc }, $push: { img: img_url, desc: '复审' } }
            }
            await mg.updateOne('admin_play_info', { _id: mg.ObjectID(_id) }, update)
            pu.fail('成功', res)
            return
        }

        if (status == 3) { //审核通过

            this.payment_succsec(res, orderinfo, status, _id)


        } else {
            pu.fail('状态不正确', res)
        }

    }


    /*首次提交支付信息*/
    async sublime_payment_info (req, res, next) {

        let version_id = req.body.version_id //版本id
        let name = req.body.name //提交人名字
        let people_id = req.body.people_id //人数id
        let time_id = req.body.time_id  //时间id
        let group_name = req.body.group_name //团队名字
        let img_url = req.body.img_url || '' //凭证地址
        let bank_name = req.body.bank_name || ''//银行名字
        let bank_code = req.body.bank_code || '' //银行账号
        let bank_address = req.body.bank_address || '' //银行账号
        let type = req.body.type// 0线下支付  1微信支付 2支付宝支付
        if (type == 0) {
            //  img_url, 
            let isnull = pu.isnull([version_id, people_id, time_id, group_name,bank_name, bank_code])
            if (isnull) {
                pu.fail('参数不正确', res)
                return
            }
        }
        if (type == 1 || type == 2) {
            let isnull = pu.isnull([version_id, people_id, time_id])
            if (isnull) {
                pu.fail('参数不正确', res)
                return
            }
        }

        if (type == 1) {
            pu.fail('暂未开通微信支付', res)
            return

        }

        var teaminfo = await mg.findOne('team', { userid: mg.ObjectID(req.headers.userid) })
        if (teaminfo || (teaminfo && teaminfo.use_stop_time > new Date().getTime())) {
            pu.fail('该账号已经开通团队', res)
            return
        }

        name=name?  teaminfo.phone.toString().slice(3) + "****"+  teaminfo.phone.toString().slice(7,11):name;
        let people = await redis.lrange('ADMIN_PLAYINFO_PEOPLE')
        let time = await redis.lrange('ADMIN_PLAYINFO_TIME')
        let version = await redis.lrange('ADMIN_PLAYINFO_VERSION')


        var p_info = {}
        for (var i = 0; i < people.length; i++) {
            if (people[i]) {
                let pipoleinfo = JSON.parse(people[i])
                if (people_id == pipoleinfo.id) {
                    p_info = pipoleinfo
                }
            }
        }
        var t_info = {}
        for (var i = 0; i < time.length; i++) {
            if (time[i]) {
                let timeinfo = JSON.parse(time[i])
                if (time_id == timeinfo.id) {
                    t_info = timeinfo
                }
            }
        }
        var v_info = {}
        for (var i = 0; i < version.length; i++) {
            if (version[i]) {
                let versioninfo = JSON.parse(version[i])
                if (version_id == versioninfo.id) {
                    v_info = versioninfo
                }
            }
        }
        if (type == 0) {
            let orderinfo = await mg.findOne('admin_play_info', { userid: mg.ObjectID(req.headers.userid), status: 0, type: 0 })
            if (orderinfo) {
                pu.fail('账号还有未通过审核订单', res)
                return
            }
        }
        if (JSON.stringify(t_info) == '{}') {
            pu.fail('请选择时间', res)
            return
        }
        if (JSON.stringify(v_info) == '{}') {
            pu.fail('请选择版本', res)
            return
        }
        if (JSON.stringify(p_info) == '{}') {
            pu.fail('请选择支付信息', res)
            return
        }

        var money = Number(t_info.discount) * Number(v_info.price) * Number(p_info.sum) * Number(p_info.discount)

        /*订单信息*/
        var inserInfo = {
            money: money,
            userid: mg.ObjectID(req.headers.userid),
            name: name,
            type: Number(type), //线下支付订单
            v_info: v_info,
            t_info: t_info,
            p_info: p_info,
            group_name: group_name,
            img_url: [{ img: img_url, desc: '首次提交' }],
            bank_name: bank_name,
            bank_code: bank_code,
            bank_address: bank_address,
            desc: '',
            is_delete: 0,
            status: money == 0 ? 3 : 0  //0审核中  1审核不通过直接驳回  2 补差价 3通过
        }
        if (version_id == config.test.testversion && people_id == config.test.testPople && time_id == config.test.testTime) {
            let inserrawo = await mg.insertOne('admin_play_info', inserInfo)
            let id = inserrawo.insertedId
            this.payment_succsec('', inserInfo, 3, id)
            pu.success('OK', inserInfo, res)
            return
        }

        /*生成支付订单*/


        if (type == 2) {


            let inserrawo = await mg.insertOne('admin_play_info', inserInfo)
            let id = inserrawo.insertedId
            let url = await aliplay.play(id.toString(), '0.01', inserInfo.name)
            pu.success('OK', { url: url, id: id }, res)

        } else {
            mg.insertOne('admin_play_info', inserInfo)
            pu.success('OK', inserInfo, res)
        }


    }

    /*获取文件上传token*/
    async get_qiuniu_token (req, res, next) {
        let token = wx.getauthKey()
        pu.success('OK', token, res)

    }
}

module.exports = new play()
